import React, { useContext, useState, useMemo } from 'react'
import Mynav from './components/Mynav'
import Ctx from '../store/Ctx'
import { Tabs, ProductCard, Tag, Button, Space, Toast } from 'react-vant'
import { Star } from '@react-vant/icons';

export default function Home(props) {

  //从父组件中获取数据
  let obj = useContext(Ctx)
  //console.log(obj);

  //定义一个下标
  let [index, sedIndex] = useState(0)

  //通过useMemo缓存属性 进行筛选 点击对应的标签页显示对应的数据
  let newlist = useMemo(() => {
    return obj.datalist.filter(item => {
      if (index == 0) {
        return item
      }
      return item.typeId == index
    })
  }, [obj.datalist, index])

  return (
    <div>

      {/* 导航栏 */}
      <Mynav title={'首页'} leftText={false}></Mynav>

      {/* 标签页 */}
      <Tabs onChange={(e) => {
        sedIndex(e)
      }}>
        {['全部', '推荐', '小说', '儿童'].map(item => (
          <Tabs.TabPane key={item} title={item}></Tabs.TabPane>
        ))}
      </Tabs>

      {/* 商品卡片组件 渲染数据 */}
      <div className='alllist'>
        {
          newlist.map(item => {
            return <ProductCard onClick={() => {
              //点击切换到详情页
              props.history.push({
                pathname: '/details',
                state: item.id
              })
            }}
              key={item.id}
              num={<>
                <Space>
                  <span style={{ position: 'relative', top: '5px' }}
                    onClick={(c) => {
                      //阻止事件冒泡
                      c.stopPropagation()
                      //切换状态时的轻提示
                      if (item.collect) {
                        Toast.info('取消收藏')
                      } else {
                        Toast.info('收藏成功')
                      }
                      //切换收藏状态的方法
                      obj.dispatch({
                        type: 'change_collect',
                        payload: item.id
                      })
                    }}>
                    <Star color={item.collect ? 'red' : ''} />
                  </span>
                  <Button round size='mini' type={item.sub ? 'warning' : 'default'}
                    onClick={(c) => {
                      //阻止事件冒泡
                      c.stopPropagation()
                      //切换状态时的轻提示
                      if (item.sub) {
                        Toast.info('取消订阅')
                      } else {
                        Toast.info('订阅成功')
                      }
                      //切换订阅的方法
                      obj.dispatch({
                        type: 'change_sub',
                        payload: item.id
                      })
                    }}>
                    {item.sub ? '已经订阅' : '免费订阅'}
                  </Button>
                </Space>
              </>}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }
      </div>

    </div>
  )
}
